import React from 'react';
import {Button, Card, Form, Select, Modal, Table, message, Input, Tree, Radio, Menu, Transfer,} from 'antd';
import axios from './../../axios';
import Utils from './../../utils/utils';
import BaseForm from './../../components/BaseForm';
import ETable from './../../components/ETable';
import menuConfig from './../../config/menuConfig';


const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;

export default class Role extends React.Component {
    params = {
        page: 1
    };

    state = {
        isVisible: false,
        isEditVisible: false
    };

    formList = [
        {
            type: 'INPUT',
            label: '用户名',
            field: 'user_name',
            width: 250,
            placeholder: '请输入用户名称',
        },
        {
            type: 'INPUT',
            label: '用户手机号',
            width: 250,
            field: 'user_phone',
            placeholder: '请输入手机号',
        },
        {
            type: 'DATE',
            label: '请选择入职日期',
            field: 'user_date',
            width: 250,
            placeholder: '请输入日期',
        },
    ];


    componentDidMount() {
        this.requestList()
    }

// /筛选框查询
    filterSearch = (params) => {
        this.params = params;
        this.requestList();

    };

    //请求查询数据
    requestList = () => {
        axios.requestList('/role/list', this.params, this)

    };

    //处理各类请求
    handleRoleCreate = () => {
        this.setState({
            isVisible: true
        })
    };


    //保存角色
    handleRoleSubmit = () => {

        let data = this.roleForm.props.form.getFieldsValue();
        axios.ajax({
            url: 'role/create',
            data: {
                params: {
                    ...data
                }
            }
        }).then((res) => {
            if (res.code == '0') {
                this.roleForm.props.form.resetFields();
                this.setState({
                    isVisible: false
                });
                message.success({
                    content: '创建成功！'

                })
                this.requestList();
            }

        })

    };


    //设置权限
    handleEdit = () => {
        //选择记录
        let item = this.state.selectedItem;
        console.log('item', item);


        if (!item) {
            Modal.info({
                title: '提示',
                content: '请选择一条记录'
            })
            return;
        }
        this.setState({
            isEditVisible: true,
            title: '设置权限',
            editInfo: item,
            menuInfo: item.menus
        })


    };


    //保存设置权限
    handleEditSubmit = () => {

        let data = this.editForm.props.form.getFieldsValue();
        //往data对象里面添加属性
        data.role_id = this.state.selectedItem.id;
        data.menus = this.state.menuInfo;
        axios.ajax({
            url: '/permission/edit',
            data: {
                params: {
                    ...data
                }
            }
        }).then((res) => {
            if (res.code == '0') {
                this.editForm.props.form.resetFields();
                this.setState({
                    isEditVisible: false
                });
                message.success({
                    content: '保存权限成功！'

                })
                this.requestList();
            }

        })


    };


    //用户授权
    handleUserAuth = () => {
        //选择记录
        let item = this.state.selectedItem;
        console.log('item', item);


        if (!item) {
            Modal.info({
                title: '提示',
                content: '请选择一条记录'
            })
            return;
        }

        this.setState({
            isAuthVisible: true,
            authInfo: item
        });
        this.getRoleList(item.id)


    };

    //获取用户数据
    getRoleList = (id) => {
        axios.ajax({
            url: '/role/user_list',
            data: {
                params: {
                    id
                }
            }
        }).then((res) => {
            if (res) {

                this.getAuthUserList(res.result)
            }
        })

    };

    //右侧筛选目标用户
    getAuthUserList = (dataSource) => {

        const mockData = [];   //
        const targetKeys = [];
        if (dataSource && dataSource.length > 0) {
            for (let i = 0; i < dataSource.length; i++) {
                const data = {
                    key: dataSource[i].user_id,
                    title: dataSource[i].user_name,
                    statue: dataSource[i].status,

                }

                if (data.status == 1) {
                    //key的集合
                    targetKeys.push(data.key)
                }
                mockData.push(data)

            }
            this.setState({
                mockData,
                targetKeys

            })
        }


    };
    //提交保存授权的数据
    handleAuthSubmit = () => {
        let data = {};
        //作为参数传给后台，
        console.log('this.state.targetKeys',this.state.targetKeys)
        data.user_ids = this.state.targetKeys;
        data.role_id = this.state.selectedItem.id;
        axios.ajax({
            url:'/role/user_role_edit',
            data:{
                params:{
                    user_ids :data.user_ids,
                    role_id :data.role_id
                }
            }
        }).then((res) => {
            if (res.code == '0') {
                this.authForm.props.form.resetFields();
                this.setState({
                    isAuthVisible: false
                });
                message.success({
                    content: '保存权限成功！'

                });
                this.requestList();
            }
        })

    };


    render() {

        const columns = [
            {
                title: '角色ID',
                dataIndex: 'id'
            }, {
                title: '角色名称',
                dataIndex: 'role_name'
            }, {
                title: '创建时间',
                dataIndex: 'create_time',
                render: Utils.formatDate
            }, {
                title: '使用状态',
                dataIndex: 'status',
                //
                render(status) {
                    return status === 1 ? '启用' : '停用'
                }
            }, {
                title: '授权时间',
                dataIndex: 'authorize_time',
                //日期格式转换
                render: Utils.formatDate
            }, {
                title: '授权人',
                dataIndex: 'authorize_user_name',
            }
        ];

        //动态控制foot显示与否
        let footer = {}
        if (this.state.type === 'detail') {
            footer = {
                footer: null
            }
        }
        return (
            <div>
                <Card>
                    <BaseForm formList={this.formList} filterSearch={this.filterSearch}/>
                </Card>
                <Card style={{marginTop: 10}}>
                    <Button type="primary" icon="plus" onClick={this.handleRoleCreate}>创建角色</Button>
                    <Button type="primary" icon="edit" style={{marginLeft: 20}}
                            onClick={this.handleEdit}>设置权限</Button>
                    <Button type="primary" style={{marginLeft: 20}}
                            onClick={this.handleUserAuth}>用户授权</Button>
                </Card>
                <div className="content-wrap">

                    <ETable
                        updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                        columns={columns}
                        rowSelection='radio'
                        dataSource={this.state.list}
                        pagination={this.state.pagination}
                        selectedRowKeys={this.state.selectRowKeys}
                        selectedIds={this.state.selectedIds}
                        selectedItem={this.state.selectedItem}

                    />
                </div>
                <Modal
                    title={this.state.title}
                    onOk={this.handleRoleSubmit}
                    visible={this.state.isVisible}
                    onCancel={() => {
                        this.roleForm.props.form.resetFields();
                        this.setState({
                            isVisible: false
                        })
                    }}
                    width={600}
                    {...footer}
                >
                    <RoleForm
                        //方便使用子组件的props：
                        wrappedComponentRef={(inst) => {
                            this.roleForm = inst
                        }}/>

                </Modal>


                <Modal
                    title={this.state.title}
                    onOk={this.handleEditSubmit}
                    visible={this.state.isEditVisible}
                    onCancel={() => {
                        this.roleForm.props.form.resetFields();
                        this.setState({
                            isEditVisible: false
                        })
                    }}
                    width={600}
                    {...footer}
                >
                    <EditForm
                        editInfo={this.state.editInfo}
                        menuInfo={this.state.menuInfo}
                        //方便使用子组件的props：
                        wrappedComponentRef={(inst) => {
                            this.editForm = inst
                        }}
                        patchMenuInfo={(checkedKeys) => {
                            this.setState({
                                //子组件传过来最新的选择好的值
                                menuInfo: checkedKeys
                            })
                        }}


                    />

                </Modal>
                <Modal
                    title="用户授权"
                    onOk={this.handleAuthSubmit}
                    visible={this.state.isAuthVisible}
                    onCancel={() => {
                        // this.roleForm.props.form.resetFields();
                        this.setState({
                            isAuthVisible: false
                        })
                    }}
                    width={600}
                    {...footer}
                >
                    <RoleAuthForm
                        authInfo={this.state.authInfo}
                        mockData={this.state.mockData}
                        targetKeys={this.state.targetKeys}
                        patchAuthChange={(targetKeys) => {
                            this.setState({
                                //子组件传过来最新的选择好的值
                                targetKeys: targetKeys
                            })
                        }}
                        wrappedComponentRef={(inst) => {
                            this.authForm = inst
                        }}


                    />

                </Modal>


            </div>
        );
    }


}


class RoleForm extends React.Component {

    render() {
        const {getFieldDecorator} = this.props.form;
        const userInfo = this.props.userInfo || {};


        const formItemLayout = {
            labelCol: {
                span: 5

            },
            wrapperCol: {
                span: 15
            }
        };


        return (
            <div>
                <Form layout="horizontal">

                    <FormItem label="角色名称" {...formItemLayout}>

                        {
                            getFieldDecorator('role_name', {})(
                                <Input type="text" placeholder="请输入姓名"/>
                            )
                        }
                    </FormItem>

                    <FormItem label="状态" {...formItemLayout}>
                        {
                            getFieldDecorator('state', {})(
                                <Select>
                                    <Option value={1}>开启</Option>
                                    <Option value={2}>关闭</Option>
                                </Select>
                            )}
                    </FormItem>
                </Form>
            </div>
        );
    }


}

RoleForm = Form.create()(RoleForm);


class EditForm extends React.Component {

    onCheck = (checkedKeys) => {
        this.props.patchMenuInfo(checkedKeys);
    }


    //遍历树形结构
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.key}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                )
            }
            return <TreeNode {...item}/>
        })
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const editInfo = this.props.editInfo || {};
        const menuInfo = this.props.menuInfo || {};


        const formItemLayout = {
            labelCol: {
                span: 5

            },
            wrapperCol: {
                span: 15
            }
        };


        return (
            <div>
                <Form layout="horizontal">

                    <FormItem label="角色名称" {...formItemLayout}>

                        {
                            getFieldDecorator('role_name', {})(
                                <Input type="text" placeholder={editInfo.role_name}/>
                            )
                        }
                    </FormItem>

                    <FormItem label="状态" {...formItemLayout}>
                        {
                            getFieldDecorator('state', {
                                initialValue: 1

                            })(
                                <Select>
                                    <Option value={1}>开启</Option>
                                    <Option value={2}>关闭</Option>
                                </Select>
                            )}
                    </FormItem>
                    <Tree
                        checkable
                        defaultExpandAll
                        //修改之后需要调用父组件的方法流回父组件，单向的数据流，

                        onCheck={(checkedKeys) => {
                            this.onCheck(checkedKeys)
                        }}
                        //接口中返回的原本该用户下面原本就有的权限菜单（会被打勾）
                        checkedKeys={menuInfo}
                    >
                        <TreeNode title="平台权限" key="platform_all">
                            {this.renderTreeNodes(menuConfig)}
                        </TreeNode>

                    </Tree>
                </Form>
            </div>
        );
    }


}

EditForm = Form.create()(EditForm);


class RoleAuthForm extends React.Component {

    //搜索框
    filterOption(inputValue, option) {
        return option.title.indexOf(inputValue) > -1;
    }


    //子组件数据流回父组件
    handleAuthChange = (targetKeys) => {
        console.log('this.props', this.props);
        this.props.patchAuthChange(targetKeys);

    };


    render() {
        const {getFieldDecorator} = this.props.form;
        const authInfo = this.props.authInfo || {};
        const targetKeys = this.props.targetKeys || {};


        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 18}
        };

        return (
            <div>
                <Form layout="horizontal">
                    <FormItem label="角色名称：" {...formItemLayout}>
                        <Input disabled maxLength={8} placeholder={authInfo.role_name}/>
                    </FormItem>
                    <FormItem label="选择用户：" {...formItemLayout}>
                        <Transfer
                            // listStyle={{width: 200,height: 400}}
                            dataSource={this.props.mockData}
                            showSearch
                            titles={['待选用户', '已选用户']}
                            searchPlaceholder='输入用户名'
                            filterOption={this.filterOption}
                            targetKeys={this.props.targetKeys}
                            onChange={this.handleAuthChange}
                            render={item => item.title}
                        />
                    </FormItem>
                </Form>
            </div>
        );
    }
}

RoleAuthForm = Form.create()(RoleAuthForm);


